package com.quartet.modules.customer.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quartet.api.ApiResult;
import com.quartet.api.MapServerException;
import com.quartet.api.PageResult;
import com.quartet.api.ResultErrorEnum;
import com.quartet.modules.customer.dto.TCustomerInfoAddRequestDto;
import com.quartet.modules.customer.dto.TCustomerInfoQueryRequestDto;
import com.quartet.modules.customer.dto.TCustomerInfoResponseDto;
import com.quartet.modules.customer.entity.TCustomerInfo;
import com.quartet.modules.customer.service.TCustomerInfoService;
import com.quartet.modules.order.entity.TOrder;
import com.quartet.modules.order.service.TOrderService;
import com.quartet.modules.stock.entity.TTerminalStock;
import com.quartet.modules.stock.service.TTerminalStockService;
import com.quartet.modules.terminal.dto.TTerminalInfoResponseDto;
import com.quartet.modules.terminal.entity.TTerminalInfo;
import com.quartet.modules.terminal.service.TTerminalInfoService;
import com.quartet.utils.BeanTool;
import com.quartet.utils.RandomUtils;
import com.quartet.utils.SecurityUtils;
import com.quartet.utils.constant.MapServerConstant;
import com.quartet.validation.AddValidation;
import com.quartet.validation.UpdateValidation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 客户信息表(TCustomerInfo)表控制层
 *
 * @author makejava
 * @since 2021-05-04 16:25:16
 */
@RestController
@RequestMapping("tCustomerInfo")
@Slf4j
@Api(tags = "业务：客户管理")
public class TCustomerInfoController {
    /**
     * 服务对象
     */
    @Resource
    private TCustomerInfoService tCustomerInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TTerminalInfoService tTerminalInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TTerminalStockService tTerminalStockService;
    /**
     * 服务对象
     */
    @Resource
    private TOrderService tOrderService;

    /**
     * 分页查询所有数据
     *
     * @param tCustomerInfoRequestDto 查询实体
     * @return 所有数据
     */
    @ApiOperation("分页查询所有客户信息")
    @PostMapping("/query-page")
    public ApiResult<PageResult> selectCustomerPage(@RequestBody TCustomerInfoQueryRequestDto tCustomerInfoRequestDto) {
        log.info("---------selectCustomerPage begin, tCustomerInfoRequestDto is {}----------", tCustomerInfoRequestDto);
        IPage<TCustomerInfo> page = new Page<>(tCustomerInfoRequestDto.getCurrent(), tCustomerInfoRequestDto.getLimit());
        QueryWrapper<TCustomerInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(tCustomerInfoRequestDto.getCustomerName())) {
            queryWrapper.lambda().like(TCustomerInfo::getCustomerName, tCustomerInfoRequestDto.getCustomerName());
        }
        if (StringUtils.isNotBlank(tCustomerInfoRequestDto.getCreateUsername())) {
            queryWrapper.lambda().like(TCustomerInfo::getCreateUsername, tCustomerInfoRequestDto.getCreateUsername());
        }
        if (StringUtils.isNotBlank(tCustomerInfoRequestDto.getContacts())) {
            queryWrapper.lambda().like(TCustomerInfo::getContacts, tCustomerInfoRequestDto.getContacts());
        }

        if (!ObjectUtils.isEmpty(tCustomerInfoRequestDto.getCreateStartTime())) {
            queryWrapper.lambda().ge(TCustomerInfo::getCreateTime, tCustomerInfoRequestDto.getCreateStartTime());
        }
        if (!ObjectUtils.isEmpty(tCustomerInfoRequestDto.getCreateEndTime())) {
            queryWrapper.lambda().le(TCustomerInfo::getCreateTime, tCustomerInfoRequestDto.getCreateEndTime());
        }
        if (StringUtils.isNotBlank(tCustomerInfoRequestDto.getField())) {
            queryWrapper.orderBy(true, tCustomerInfoRequestDto.isAsc(), tCustomerInfoRequestDto.getField());
        } else {
            queryWrapper.orderBy(true, tCustomerInfoRequestDto.isAsc(), MapServerConstant.CREATE_TIME);
        }
        IPage<TCustomerInfo> dbResult = tCustomerInfoService.page(page, queryWrapper);
        PageResult<TCustomerInfoResponseDto> pageResult = new PageResult();
        List<TCustomerInfoResponseDto> tCustomerInfoResponseDtoList = dbResult.getRecords().stream().map(tCustomerInfo -> {
            TCustomerInfoResponseDto tCustomerInfoResponseDto = BeanUtil.copyProperties(tCustomerInfo, TCustomerInfoResponseDto.class);
            return tCustomerInfoResponseDto;
        }).collect(Collectors.toList());
        pageResult.setTotal(dbResult.getTotal());
        pageResult.setData(tCustomerInfoResponseDtoList);
        log.info("---------selectCustomerPage end, data is {}----------", pageResult);
        return ApiResult.ok(pageResult);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("通过主键查询客户信息")
    @GetMapping("/selectById")
    public ApiResult<TCustomerInfoResponseDto> selectById(@RequestParam("id") String id) {
        log.info("---------selectCustomerInfoById begin, id is {}----------", id);
        TCustomerInfo tCustomerInfo = this.tCustomerInfoService.getById(id);
        TCustomerInfoResponseDto tCustomerInfoResponseDto = BeanUtil.copyProperties(tCustomerInfo, TCustomerInfoResponseDto.class);
        return ApiResult.ok(tCustomerInfoResponseDto);
    }

    /**
     * 新增数据
     *
     * @param tCustomerInfoRequestDto 实体对象
     * @return 新增结果
     */
    @ApiOperation("新增客户信息")
    @PostMapping("/add")
    public ApiResult add(@RequestBody @Validated(AddValidation.class) TCustomerInfoAddRequestDto tCustomerInfoRequestDto) {
        log.info("---------addCustomer begin, tCustomerInfoRequestDto is {}----------", tCustomerInfoRequestDto);
        TCustomerInfo tCustomerInfo = BeanUtil.copyProperties(tCustomerInfoRequestDto, TCustomerInfo.class);
        tCustomerInfo.setCustomerCode(RandomUtils.getCustomerCode());
        String currentUsername = SecurityUtils.getCurrentUsername();
        Long currentUserId = SecurityUtils.getCurrentUserId();
        tCustomerInfo.setCreateUserId(String.valueOf(currentUserId));
        tCustomerInfo.setCreateUsername(currentUsername);
        return ApiResult.ok(this.tCustomerInfoService.save(tCustomerInfo));
    }

    /**
     * 修改数据
     *
     * @param tCustomerInfoRequestDto 实体对象
     * @return 修改结果
     */
    @ApiOperation("修改客户信息")
    @PutMapping("/update")
    public ApiResult update(@RequestBody @Validated(UpdateValidation.class) TCustomerInfoAddRequestDto tCustomerInfoRequestDto) {
        log.info("---------updateCustomer begin, tCustomerInfoRequestDto is {}----------", tCustomerInfoRequestDto);
        TCustomerInfo tCustomerInfo = BeanUtil.copyProperties(tCustomerInfoRequestDto, TCustomerInfo.class);
        return ApiResult.ok(this.tCustomerInfoService.updateById(tCustomerInfo));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @ApiOperation("删除客户信息")
    @DeleteMapping("/batch-delete")
    public ApiResult delete(@RequestBody List<Integer> idList) {
        log.info("---------deleteCustomer begin, idList is {}----------", idList);
        List<TCustomerInfo> tCustomerInfoList = tCustomerInfoService.listByIds(idList);
        tCustomerInfoList.forEach(tCustomerInfo -> {
            //校验客户下面是否有订单
            QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TOrder::getCustomerCode, tCustomerInfo.getCustomerCode());
            int count = tOrderService.count(queryWrapper);
            if (count > 0) {
                throw new MapServerException(ResultErrorEnum.BMKPT003);
            }
        });
        return ApiResult.ok(this.tCustomerInfoService.removeByIds(idList));
    }

//    /**
//     * 查询客户树
//     *
//     * @return 查询结果
//     */
//    @ApiOperation("查询客户树")
//    @PostMapping("/selectCustomerTree")
//    public ApiResult<List<TCustomerInfoResponseDto>> selectCustomerTree() {
//        log.info("---------selectCustomerTree begin-------------");
//        return ApiResult.ok(this.tCustomerInfoService.selectCustomerTree());
//    }

    /**
     * 客户下拉框
     *
     * @return 结果
     */
    @ApiOperation("客户下拉框")
    @PostMapping("/selectCustomerList")
    @ApiImplicitParams({@ApiImplicitParam(name = "queryType", value = "查询类型\n" +
            "     * terminal_code：终端编码\n" +
            "     * flow_card_number：流量卡号\n" +
            "     * customer_name：客户名称")})
    public ApiResult<List<TCustomerInfoResponseDto>> selectCustomerList(@RequestParam(value = "queryType",required = false) String queryType, @RequestParam(value = "queryValue",required = false) String queryValue) {
        log.info("---------selectCustomerTree begin-------------queryType,queryValue is {},{} ",queryType,queryValue);
        if(StringUtils.isBlank(queryType)||StringUtils.isBlank(queryType)){
            List<TCustomerInfo> tCustomerInfoList = this.tCustomerInfoService.list();
            List<TCustomerInfoResponseDto> tCustomerInfoResponseDtoList = BeanTool.copyObjListProperties(tCustomerInfoList, TCustomerInfoResponseDto.class);
            return ApiResult.ok(tCustomerInfoResponseDtoList);
        }

        List<String> terminalCodeList = new ArrayList<>();
        if ("terminal_code".equals(queryType) && StringUtils.isNotBlank(queryValue)) {
            terminalCodeList.add(queryValue);
        } else if ("flow_card_number".equals(queryType) && StringUtils.isNotBlank(queryValue)) {
            TTerminalInfo one = tTerminalInfoService.getOne(new QueryWrapper<TTerminalInfo>().lambda().eq(TTerminalInfo::getFlowCardNumber, queryValue));
            if (!Objects.isNull(one)) {
                terminalCodeList.add(one.getTerminalCode());
            }
        } else if ("customer_name".equals(queryType) && StringUtils.isNotBlank(queryValue)) {
            {
                List<TCustomerInfo> tCustomerInfoList = tCustomerInfoService.list(new QueryWrapper<TCustomerInfo>().lambda().eq(TCustomerInfo::getCustomerName, queryValue));
                List<String> tCustomerCodeList = tCustomerInfoList.stream().map(TCustomerInfo::getCustomerCode).collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(tCustomerCodeList)) {
                    List<TOrder> tOrderList = tOrderService.list(new QueryWrapper<TOrder>().lambda().in(TOrder::getCustomerCode, tCustomerCodeList));
                    List<String> tOrderCodeList = tOrderList.stream().map(TOrder::getOrderCode).collect(Collectors.toList());

                    if (!CollectionUtils.isEmpty(tOrderCodeList)) {
                        List<TTerminalStock> tTerminalStockList = tTerminalStockService.list(new QueryWrapper<TTerminalStock>().lambda().in(TTerminalStock::getOrderCode, tOrderCodeList));
                        List<String> list = tTerminalStockList.stream().map(TTerminalStock::getTerminalCode).collect(Collectors.toList());
                        terminalCodeList.addAll(list);
                    }
                }
            }

        }
        List<TCustomerInfo> tCustomerInfoList = this.tCustomerInfoService.list();
        List<TCustomerInfoResponseDto> tCustomerInfoResponseDtoList = tCustomerInfoList.stream().map(tCustomerInfo -> {
            TCustomerInfoResponseDto tCustomerInfoResponseDto = BeanUtil.copyProperties(tCustomerInfo, TCustomerInfoResponseDto.class);
            List<TOrder> tOrderList = tOrderService.list(new QueryWrapper<TOrder>().lambda().eq(TOrder::getCustomerCode, tCustomerInfo.getCustomerCode()));
            List<String> orderList = tOrderList.stream().map(tOrder -> tOrder.getOrderCode()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(orderList)) {
                QueryWrapper<TTerminalStock> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().in(TTerminalStock::getOrderCode, orderList);
                List<TTerminalStock> tTerminalInfoList = tTerminalStockService.list(queryWrapper);
                List<String> terminalCodeList1 = tTerminalInfoList.stream().map(tTerminalStock -> tTerminalStock.getTerminalCode()).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(terminalCodeList1)) {
//                    QueryWrapper<TTerminalInfo> queryWrapper1 = new QueryWrapper<>();
//                    queryWrapper1.lambda().in(TTerminalInfo::getTerminalCode, terminalCodeList);
//                    List<TTerminalInfo> tTerminalInfos = tTerminalInfoService.list(queryWrapper1);
//                    List<TTerminalInfoResponseDto> tTerminalInfoResponseDtoList = BeanTool.copyObjListProperties(tTerminalInfos, TTerminalInfoResponseDto.class);
                    List<TTerminalInfoResponseDto> tTerminalInfoResponseDtoList = terminalCodeList1.stream().map(x -> {
                        TTerminalInfoResponseDto tTerminalInfoResponseDto = new TTerminalInfoResponseDto();
                        tTerminalInfoResponseDto.setTerminalCode(x);
                        if (terminalCodeList.contains(x)) {
                            tTerminalInfoResponseDto.setChecked(true);
                        } else {
                            tTerminalInfoResponseDto.setChecked(false);
                        }
                        return tTerminalInfoResponseDto;
                    }).collect(Collectors.toList());
                    tCustomerInfoResponseDto.setTTerminalInfoResponseDtoList(tTerminalInfoResponseDtoList);
                }
            }
            return tCustomerInfoResponseDto;
        }).collect(Collectors.toList());
        return ApiResult.ok(tCustomerInfoResponseDtoList);
    }
}
